package service

import (
	"encoding/json"
	"fmt"
	"monitor/src/models"
	"time"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shopspring/decimal"
)

// 获取CPU使用率，并且是计算五秒钟内的平均值
func GetCpuPercent(cpuChan chan float64) {
	var second = 5
	var sum float64 = 0
	for i := second; i > 0; i-- {
		percent, _ := cpu.Percent(time.Second, false)
		sum = sum + percent[0]
		time.Sleep(time.Second)
	}
	cpuPer, _ := decimal.NewFromFloat(sum / float64(second)).Round(2).Float64()
	cpuChan <- cpuPer
}

func GetMemPercent(memChan chan float64) {
	memInfo, _ := mem.VirtualMemory()
	menPer, _ := decimal.NewFromFloat(memInfo.UsedPercent).Round(2).Float64()
	memChan <- menPer
}

func GetDiskPercent(diskChan chan map[string]float64) {
	parts, _ := disk.Partitions(true)
	var diskList = make(map[string]float64)
	for _, v := range parts {
		diskInfo, _ := disk.Usage(v.Mountpoint)
		if diskInfo.Total > 31000000000 {
			diskList[diskInfo.Path[:1]], _ = decimal.NewFromFloat(diskInfo.UsedPercent).Round(2).Float64()
		}
	}
	diskChan <- diskList
}

// 整合CPU，内存和磁盘的数据，转换为json字符串
func GetSource(sourceChan chan string) {
	var cpuChan, memChan, diskChan = make(chan float64), make(chan float64), make(chan map[string]float64)

	go GetCpuPercent(cpuChan)
	go GetMemPercent(memChan)
	go GetDiskPercent(diskChan)
	cpuPer, menPer, diskPerList := <-cpuChan, <-memChan, <-diskChan
	var source = &models.Source{cpuPer, menPer, diskPerList}
	sourceJson, err := json.Marshal(source)
	if err != nil {
		fmt.Println(err)
		sourceChan <- ""
	} else {
		sourceChan <- string(sourceJson)
	}
}
